package com.ucode.hrm.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.hrm.controller.service.ApiHrmDataPermissionService;
import com.ucode.hrm.service.HrmAttendanceRecordService;
import com.ucode.hrm.service.HrmCustomerCompanyService;
import com.ucode.hrm.service.HrmCustomerProjectService;
import com.ucode.hrm.service.HrmEmployeeService;
import com.ucode.model.hrm.HrmAttendanceRecord;
import com.ucode.model.hrm.HrmCustomerCompany;
import com.ucode.model.hrm.HrmCustomerProject;
import com.ucode.model.hrm.HrmEmployee;
import com.ucode.model.hrm.convert.HrmAttendanceRecordConvert;
import com.ucode.model.hrm.enums.HrmAttendanceRecordsStatusEnum;
import com.ucode.model.hrm.vo.HrmAttendanceRecordVO;
import com.ucode.model.sys.user.AdminUser;
import com.ucode.ssm.user.service.AdminUserService;
import com.ucode.tool.annotation.DataPermission;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.validator.InEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Tag(name = "管理后台 - 人力资源系统 - 打卡记录")
@RestController
@RequestMapping("/hrm/attendance-record")
@Validated
public class HrmAttendanceRecordController {

    @Resource
    private HrmAttendanceRecordService hrmAttendanceRecordService;

    @Resource
    private HrmCustomerProjectService customerProjectService;
    @Resource
    private HrmCustomerCompanyService customerCompanyService;
    @Resource
    private HrmEmployeeService employeeService;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private ApiHrmDataPermissionService apiHrmDataPermissionService ;

    @GetMapping("/page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:attendance-record:query')")
    @DataPermission(permissions={"hrm:attendance-record:query"})
    public ResponseResult<Paginator<HrmAttendanceRecordVO>> pageList(
            @Schema(description = "员工编号") @RequestParam(value = "employeeId",required=false) String employeeId,
            @Schema(description = "客户公司ID") @RequestParam(value = "companyId",required=false) String companyId,
            @Schema(description = "客户公司项目ID") @RequestParam(value = "projectId",required=false) String projectId,
            @Schema(description = "打卡状态",allowableValues = {"1","2","3","4"})@InEnum(value = HrmAttendanceRecordsStatusEnum.class, message = "状态值必须是 {value}")@RequestParam(value = "status",required=false) Integer status,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        Set<Long> customerProjectIds = apiHrmDataPermissionService.getCurrentUserCustomerProjectIdsByDataPermission();
        //没有可查看的数据
        if(ObjUtil.isNotNull(customerProjectIds) && customerProjectIds.size() == 0){
            return ResponseResult.success(new Paginator<>());
        }

        //没有权限查看指定项目的数据
        if(ObjUtil.isNotNull(projectId) && ObjUtil.isNotNull(customerProjectIds) && !customerProjectIds.contains(projectId)){
            throw new UcodeServiceException(GlobalResultCodeEnum.UN_DATA_PERMISSION);
        }
        condition.put("projectIds",customerProjectIds);

        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }

        if(StrUtil.isNotBlank(employeeId))
            condition.put("userId",employeeId);
        if(StrUtil.isNotBlank(companyId))
            condition.put("companyId",companyId);
        if(StrUtil.isNotBlank(projectId))
            condition.put("projectId",projectId);

        if(status != null)
            condition.put("status",status);


        condition.put("deltag",false);

        //  查询打卡记录
        Paginator<HrmAttendanceRecord> paginator = hrmAttendanceRecordService.queryPageForList(condition,pageSize,pageNum);
        Paginator<HrmAttendanceRecordVO> paginatorVO = HrmAttendanceRecordConvert.INSTANCE.convertPage(paginator);

        if(CollUtil.isNotEmpty(paginatorVO.getList())) {
            Set<Long> customerCompanyIds = new HashSet<>();
            Set<Long> projectIds = new HashSet<>();
            Set<Long> employeeIds = new HashSet<>();
            Set<Long> processorIdIds = new HashSet<>();

            for(HrmAttendanceRecordVO vo : paginatorVO.getList()){
                customerCompanyIds.add(vo.getCompanyId());
                projectIds.add(vo.getProjectId());
                employeeIds.add(vo.getEmployeeId());
            }

            Map<Long, HrmCustomerCompany> customerCompanyMap = customerCompanyService.getMap(customerCompanyIds);
            Map<Long, HrmCustomerProject> projectMap = customerProjectService.getMap(projectIds);
            Map<Long, HrmEmployee> employeeMap = employeeService.getMap(employeeIds);
            Map<Long, AdminUser> processorMap = adminUserService.getUserMap(processorIdIds);

            paginatorVO.getList().forEach(item -> {
                HrmCustomerCompany customerCompany = customerCompanyMap.get(item.getCompanyId());
                if(customerCompany != null)
                    item.setCompanyName(customerCompany.getCompanyName());

                HrmCustomerProject project = projectMap.get(item.getProjectId());
                if(project != null)
                    item.setProjectName(project.getProjectName());

                HrmEmployee employee = employeeMap.get(item.getEmployeeId());
                if(employee != null)
                    item.setEmployeeName(employee.getRealName());

            });
        }

        return ResponseResult.success(paginatorVO);
    }

    @GetMapping("/getById/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('hrm:attendance-record:query')")
    public ResponseResult<HrmAttendanceRecordVO> getById(@PathVariable(name="id",required=true) Long id){
        // 查询
        HrmAttendanceRecord bean = hrmAttendanceRecordService.validate(id);
        HrmAttendanceRecordVO vo = HrmAttendanceRecordConvert.INSTANCE.convert(bean);

        if(ObjUtil.isNotNull(vo.getCompanyId())){
            HrmCustomerCompany customerCompany = customerCompanyService.selectByPrimaryKey(bean.getCompanyId());
            if(customerCompany != null)
                vo.setCompanyName(customerCompany.getCompanyName());
        }

        if(ObjUtil.isNotNull(vo.getProjectId())){
            HrmCustomerProject project = customerProjectService.selectByPrimaryKey(bean.getProjectId());
            if(project != null)
                vo.setProjectName(project.getProjectName());
        }

        HrmEmployee employee = employeeService.selectBaseInfoByPrimaryKey(vo.getEmployeeId());
        if(employee != null)
            vo.setEmployeeName(employee.getRealName());

        return ResponseResult.success(vo);
    }

}
